# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import re
from xml.dom import minidom

"""
生成图谱相关的各种辅助函数
"""


# 企业图谱数据、生成xml
def tupu_create_echarts_xml(node_list, edge_list):
    doc = minidom.Document()
    gexf = doc.createElement("gexf")
    gexf.setAttribute("xmlns", "http://www.gexf.net/1.2draft")
    gexf.setAttribute("version", "1.2")
    gexf.setAttribute("xmlns:viz", "http://www.gexf.net/1.2draft/viz")
    gexf.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
    gexf.setAttribute("xsi:schemaLocation", "http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd")

    graph = doc.createElement("graph")
    graph.setAttribute("defaultedgetype", "undirected")
    graph.setAttribute("mode", "static")
    attributes = doc.createElement("attributes")
    attributes.setAttribute("class", "node")
    attributes.setAttribute("mode", "static")
    attribute = doc.createElement("attribute")
    attribute.setAttribute("id", "modularity_class")
    attribute.setAttribute("title", "Modularity Class")
    attribute.setAttribute("type", "integer")
    attributes.appendChild(attribute)
    graph.appendChild(attributes)

    nodes = doc.createElement("nodes")
    for res in node_list:
        tupu_add_node(doc, nodes, res)
    graph.appendChild(nodes)

    edges = doc.createElement("edges")
    for res in edge_list:
        tupu_add_edge(doc, edges, res)
    graph.appendChild(edges)

    gexf.appendChild(graph)
    doc.appendChild(gexf)
    return doc.toprettyxml()


# 企业图谱数据、添加节点
def tupu_add_node(doc, nodes, nodelist):
    node = doc.createElement("node")
    node.setAttribute("id", nodelist["id"])
    node.setAttribute("label", nodelist["label"])
    attvalues = doc.createElement("attvalues")
    attvalue = doc.createElement("attvalue")
    attvalue.setAttribute("for", "modularity_class")
    attvalue.setAttribute("value", nodelist["value"])
    attvalues.appendChild(attvalue)
    node.appendChild(attvalues)
    viz_size = doc.createElement("viz:size")
    viz_size.setAttribute("value", nodelist["size"])
    viz_size.appendChild(doc.createTextNode(" "))
    node.appendChild(viz_size)
    nodetext = doc.createElement("nodeText")
    nodetext.setAttribute("value", nodelist["nodeText"])
    nodetext.appendChild(doc.createTextNode(" "))
    node.appendChild(nodetext)
    nodes.appendChild(node)


# 企业图谱数据、添加节点之间关系
def tupu_add_edge(doc, edges, edgelist):
    edge = doc.createElement("edge")
    edge.setAttribute("id", edgelist["id"])
    edge.setAttribute("source", edgelist["source"])
    edge.setAttribute("target", edgelist["target"])
    attvalues = doc.createElement("attvalues")
    if "edgeText" in edgelist:
        edgetext = doc.createElement("edgeText")
        edgetext.setAttribute("value", edgelist["edgeText"])
        edgetext.appendChild(doc.createTextNode(" "))
        attvalues.appendChild(edgetext)
    edge.appendChild(attvalues)
    edges.appendChild(edge)


# 对生成的echart的边进行去重，合并edgeText
def edge_distinct(edge):
    result = dict()
    for ed in edge:
        if ed["source"] + "-" + ed["target"] in result.keys():
            old_text = result[ed["source"] + "-" + ed["target"]]["edgeText"] if result[ed["source"] + "-" + ed["target"]]["edgeText"] else ""
            new_text = old_text + ", " + ed["edgeText"] if ed["edgeText"] and ed["edgeText"] not in old_text else old_text
            result[ed["source"] + "-" + ed["target"]]["edgeText"] = new_text
        elif ed["target"] + "-" + ed["source"] in result.keys():
            old_text = result[ed["target"] + "-" + ed["source"]]["edgeText"] if result[ed["target"] + "-" + ed["source"]]["edgeText"] else ""
            new_text = old_text + ", " + ed["edgeText"] if ed["edgeText"] and ed["edgeText"] not in old_text else old_text
            result[ed["target"] + "-" + ed["source"]]["edgeText"] = new_text
        else:
            result[ed["source"] + "-" + ed["target"]] = ed
    return [result[k] for k in result.keys()]


# 根据id返回企业名称或个人姓名和性别
def road_name_from_id(pid, t):
    from wlmodels.company.models import ELPost, ELPerson, ELGeti
    if t == "e":
        the_post = ELPost.objects.filter(entid=pid).first()
        return the_post.ENTNAME if the_post else ""
    elif t == "p":
        the_person = ELPerson.objects.filter(personid=pid).first()
        the_name = the_person.NAME if the_person else ""
        the_sex = "woman" if the_person.SEX == "2" else "man"
        return [the_name, the_sex]
    elif t == "g":
        the_post = ELGeti.objects.filter(entid=pid).first()
        return the_post.ENTNAME if the_post else ""
    return ""


# 根据neo4j返回的报文生成路径图所需的id
def road_id_from_dict(v):
    if isinstance(v, dict) and "company" in v:
        return "e" + v["company"]["companyId"]
    elif isinstance(v, dict) and "person" in v:
        return "p" + v["person"]["personId"]
    elif isinstance(v, dict) and "geti" in v:
        return "g" + v["geti"]["getiId"]
    return ""


# 对生成的边进行去重，合并relation
def road_edge_distinct(edge):
    result = dict()
    for ed in edge:
        if ed["source"] + "-" + ed["target"] in result.keys():
            old_text = result[ed["source"] + "-" + ed["target"]]["relation"] if result[ed["source"] + "-" + ed["target"]]["relation"] else ""
            new_text = old_text + ", " + ed["relation"] if ed["relation"] and ed["relation"] not in old_text else old_text
            result[ed["source"] + "-" + ed["target"]]["relation"] = new_text
        elif ed["target"] + "-" + ed["source"] in result.keys():
            old_text = result[ed["target"] + "-" + ed["source"]]["relation"] if result[ed["target"] + "-" + ed["source"]]["relation"] else ""
            new_text = old_text + ", " + ed["relation"] if ed["relation"] and ed["relation"] not in old_text  else old_text
            result[ed["target"] + "-" + ed["source"]]["relation"] = new_text
        else:
            result[ed["source"] + "-" + ed["target"]] = ed
    return [result[k] for k in result.keys()]


# 根据投资比例和投资金额，生成边上显示用的文字
def gen_touzi_edgetext(conp, cona, direction=">"):
    try:
        conp = float(conp)
    except:
        conp = 0.0
    try:
        cona = float(cona)
    except:
        cona = 0.0
    if conp:
        if 0 < conp <= 1:
            conp *= 100
        the_text = '%.4f' % conp
        # 去掉末尾的0
        the_text = re.sub("(\.\d*[1-9]+)0+$", r"\1", the_text)
        the_text = re.sub("\.0+$", "", the_text)
        # 如果在区间范围内，加百分号
        if float(the_text) <= 100:
            the_text += "%"
    elif cona:
        the_text = '%.1f万' % cona
        # 去掉末尾的0
        the_text = the_text.replace(".0万", "万")
    else:
        the_text = ""
    if the_text and direction == ">":
        the_text = "投资(%s)" % the_text
    elif the_text and direction == "<":
        the_text = "股东(%s)" % the_text
    elif not the_text and direction == ">":
        the_text = "投资"
    else:
        the_text = "股东"
    return the_text
